package com.cosyhut.blocks.display;

import java.util.logging.Level;

import com.jme.app.*;
import com.jme.util.*;

import com.cosyhut.blocks.engine.*;
import com.cosyhut.blocks.factory.*;

public class Game {

    GInput _input;
    /**
     * Simply an easy way to get at timer.getTimePerFrame(). Also saves time so
     * you don't call it more than once per frame.
     */
    protected float tpf;

    private Engine _engine;

    private GWindow _window;

    private GRenderer _renderer;

    private int _FPS;

    /** Flag for running the system. */
    protected boolean finished;

    // Frame-rate managing stuff
    private Timer timer;

    private int frames = 0;

    private long startTime;

    private long preferredTicksPerFrame;

    private long frameStartTick;

    private long frameDurationTicks;

    /**
     * Set preferred frame rate. The main loop will make every attempt to
     * maintain the given frame rate. This should not be called prior to the
     * application being <code>start()</code> -ed.
     * 
     * @param fps
     *            the desired frame rate in frames per second
     */
    public void setFrameRate(int fps) {
        if (fps <= 0) {
            throw new IllegalArgumentException(
                    "Frames per second cannot be less than one.");
        }

        LoggingSystem.getLogger().log(Level.INFO,
                "Attempting to run at " + fps + " fps.");
        preferredTicksPerFrame = timer.getResolution() / fps;
    }

    /**
     * Gets the current frame rate.
     * 
     * @return the current number of frames rendering per second
     */
    public float getFramesPerSecond() {
        float time = (timer.getTime() - startTime)
                / (float) timer.getResolution();
        float fps = frames / time;

        startTime = timer.getTime();
        frames = 0;

        return fps;
    }

    /**
     * <code>startFrame</code> begin monitoring the current frame. This method
     * should be called every frame before update and drawing code.
     */
    private void startFrame() {
        frameStartTick = timer.getTime();
    }

    /**
     * <code>endFrame</code> ends the current frame. Pads any excess time in
     * the frame by sleep()-ing the thread in order to maintain the desired
     * frame rate. No attempt is made to rectify frames which have taken too
     * much time.
     */
    private void endFrame() {
        frames++;

        frameDurationTicks = timer.getTime() - frameStartTick;

        while (frameDurationTicks < preferredTicksPerFrame) {
            long sleepTime = ((preferredTicksPerFrame - frameDurationTicks) * 1000)
                    / timer.getResolution();

            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                LoggingSystem.getLogger().log(Level.WARNING,
                        "Error sleeping during main loop.");
            }

            frameDurationTicks = timer.getTime() - frameStartTick;
        }
    }

    /**
     * Render and update logic at a specified fixed rate.
     */
    public final void start() {
        LoggingSystem.getLogger().log(Level.INFO, "Application started.");
        try {
            initSystem();

            timer = Timer.getTimer();
            setFrameRate(60); // default to 60 fps

            initGame();

            // main loop
            while (!finished && !this._window.isClosing()) {
                startFrame();

                // update game state, do not use interpolation parameter
                update();

                // render, do not use interpolation parameter
                this._renderer.update();

                endFrame();

                Thread.yield();
            }

        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            cleanup();
        }
        LoggingSystem.getLogger().log(Level.INFO, "Application ending.");

        quit();
    }

    /**
     * Quits the program abruptly using <code>System.exit</code>.
     * 
     * @see AbstractGame#quit()
     */
    protected void quit() {
        this._window.close();
        System.exit(0);
    }

    public static void main(String[] args) {
        LoggingSystem.getLogger().setLevel(Level.WARNING);
        Game _g = new Game();
        _g.start();
    }

    public void update() {
        /** Recalculate the framerate. */
        timer.update();
        /** Update tpf to time per frame according to the Timer. */
        tpf = timer.getTimePerFrame();
        this._input.update(tpf);

        // Execute updateQueue item
        GameTaskQueueManager.getManager().getQueue(GameTaskQueue.UPDATE)
                .execute();

        if (this._input.isFinished()) {
            finish();
        }
        this._engine.update();
    }

    /**
     * @see AbstractGame#initSystem()
     */
    public void initSystem() {
        this._FPS = 33;

        this._window = new GWindow();
        this._engine = Engine.get();
        this._engine.setFPS(this._FPS);

        /** Create rootNode */
        this._renderer = new GRenderer(this._window.getDisplay());
        BFactory factory = BFactory.get();
        factory.init(this._engine, this._renderer);
        
        this._input = new GInput(this._renderer.getCamera(), this._engine.getRobot().getRoot());
        /** Create a basic input controller. */
//        ThirdPersonHandler thirdPersonHandler = new ThirdPersonHandler(
//        		this._engine.getRobot().getRoot(), this._renderer.getCamera());
//        thirdPersonHandler.addToAttachedHandlers(chaser);
        
//        thirdPersonHandler.setDoGradualRotation(true);
//        thirdPersonHandler.setRotateOnly(true);
//        input = thirdPersonHandler;
        

        /** Get a high resolution timer for FPS updates. */
        timer = Timer.getTimer();

    }

    /**
     * @see AbstractGame#initGame()
     */
    public void initGame() {
        this.setFrameRate(this._FPS);

        timer.reset();


    }

    /**
     * @see AbstractGame#reinit()
     */
    public void reinit() {

    }

    /**
     * @see AbstractGame#cleanup()
     */
    public void cleanup() {

    }

    public void finish() {
        finished = true;
    }

}
